import express from 'express';

const TARGET = process.env.TARGET || 'https://care.yipuwh.com';
const app = express();
const PORT = process.env.PORT || 3000;

app.set('trust proxy', true);

// 健康检查
app.get('/_health', (_, res) => res.status(200).send('ok'));

// 反代逻辑
app.use(async (req, res) => {
  try {
    const incomingURL = new URL(req.protocol + '://' + req.get('host') + req.originalUrl);
    const targetURL = new URL(TARGET);
    targetURL.pathname = incomingURL.pathname;
    targetURL.search = incomingURL.search;

    const headers = new Headers(req.headers);
    const upstreamRes = await fetch(targetURL.toString(), {
      method: req.method,
      headers: headers,
      body: req.method === 'GET' || req.method === 'HEAD' ? undefined : req,
      redirect: 'manual',
    });

    if (upstreamRes.status >= 300 && upstreamRes.status < 400) {
      const loc = upstreamRes.headers.get('Location');
      if (loc) {
        const rewritten = loc.replace(targetURL.origin, incomingURL.origin);
        const h = new Headers(upstreamRes.headers);
        h.set('Location', rewritten);
        res.set(h);
        return res.status(upstreamRes.status).end();
      }
    }

    const ct = upstreamRes.headers.get('content-type') || '';
    const headersResponse = new Headers(upstreamRes.headers);
    if (ct.includes('text/html')) {
      const html = await upstreamRes.text();
      const rewrittenHTML = html.replaceAll(targetURL.origin, incomingURL.origin);
      headersResponse.set('content-length', String(Buffer.byteLength(rewrittenHTML)));
      return res.status(upstreamRes.status).send(rewrittenHTML);
    } else {
      upstreamRes.body.pipe(res);
    }
  } catch (error) {
    console.error('Error in proxy', error);
    return res.status(502).send('Bad Gateway');
  }
});

// 必须暴露出一个函数，作为入口
export const main = app;  // 这样平台才会调用到
